package dom.xpath.query.xpath.func;

import dom.xpath.data.Data;
import dom.xpath.query.EvalException;
import dom.xpath.query.xpath.XPContext;
import dom.xpath.query.xpath.expr.Expression;
import dom.xpath.query.xpath.values.Literal;
import dom.xpath.query.xpath.values.NodeSet;
import dom.xpath.query.xpath.values.Item;
import dom.xpath.util.Token;

/**
 * Constructor for name() function.
 * 
 * @author Workgroup DBIS, University of Konstanz 2005-07, ISC License
 * @author Tim Petrowsky
 */
public final class Name extends Func {
  /**
   * Function Constructor.
   * @param arg expression array
   */
  public Name(final Expression[] arg) {
    super(arg, "name(nodeset?)");
  }

  @Override
  public Literal eval(final XPContext ctx) throws EvalException {
    final Item[] v = evalArgs(ctx);
    final NodeSet set = v.length != 0 && v[0].size() != 0 ?
        (NodeSet) v[0] : ctx.local;

    final Data data = ctx.local.data;
    final int node = set.nodes[0];
    final int kind = data.kind(node);
    if(kind == Data.ELEM) return new Literal(data.tag(node));
    if(kind == Data.ATTR) return new Literal(data.attName(node));
    return new Literal(Token.EMPTY);
  }

  @Override
  public boolean checkArguments() {
    return args.length == 0 || args.length == 1 &&
      args[0].returnedValue() == NodeSet.class;
  }
}
